package com.kbbywyclient.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kbbywyclient.app.Key;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Jiangzx on 2017/4/25.
 */

public class OkHttpUtils {
    private static final long CONNECTION_TIME_OUT=60L;
    private static final long READ_TIME_OUT =60L;
    private static final TimeUnit TIME_UNIT=TimeUnit.SECONDS;
    private OkHttpUtils(){

    }

    private static OkHttpClient okHttpClient;

    public static OkHttpClient getOkHttpClient(){
        if(okHttpClient==null){
            synchronized (OkHttpUtils.class){
                if(okHttpClient==null){
                    okHttpClient=new OkHttpClient.Builder().
                            connectTimeout(CONNECTION_TIME_OUT,TIME_UNIT).
                            readTimeout(READ_TIME_OUT,TIME_UNIT).
                            build();
                }
            }
        }
        return okHttpClient;
    }

    /**
     * okhttp发起post请求，直接返回阿里巴巴jsonObject对象
     * @param url
     * @param params
     */
    public static Observable<JSONObject> postData(String url,Map<String,Object> params){
        final OkHttpClient client=getOkHttpClient();
        final FormBody.Builder builder=new FormBody.Builder();
        if(params!=null){
            RsaJsonUtil jsonUtil=new RsaJsonUtil();
            for(Map.Entry<String,Object> entry:params.entrySet()){
                jsonUtil.put(entry.getKey(),entry.getValue());
            }
            builder.add("params",jsonUtil.getRsaParams());
        }
        final Request request=new Request.Builder().url(url).post(builder.build()).build();
        return Observable.create((Observable.OnSubscribe<JSONObject>) subscriber -> {
            try{
                Response response=client.newCall(request).execute();
                if(response.isSuccessful()){
                    String result=response.body().string();
                    if(!result.startsWith("{")){
                        result=RSAUtil.decryptByPrivateKey(result, Key.privateKey);
                    }
                    LogUtil.d("url:"+url+"\n"+
                            "params:"+JsonAndObject.object2Json(params)+ "\n"+
                            result);
                    subscriber.onNext(JSON.parseObject(result));
                    subscriber.onCompleted();
                }else{
                    Exception e=new RuntimeException("网络异常，请稍后再试");
                    subscriber.onError(e);
                }
            }catch (Exception e){
                e.printStackTrace();
                if(e instanceof ConnectException){
                    subscriber.onError(new RuntimeException("网络异常，请检查网络设置"));
                }else if(e instanceof SocketTimeoutException){
                    subscriber.onError(new RuntimeException("服务器连接超时，请稍后再试"));
                }else {subscriber.onError(e);}
            }
        });
    }
}
